const http = require('http');
const app = require('./app');
const config = require('./config');

const server = http.createServer(app);

server.once('error', (err) => {
  console.log('Failed to start server: %s', err);
  cleanup();
  process.exit(1);
});

const cleanup = () => {
  server.close();
};

process
  .once("SIGINT", () => {
    console.log("SIGINT received");
    cleanup();
  })
  .once("SIGTERM", () => {
    console.log("SIGTERM received");
    cleanup();
  })
  .on('unhandledRejection', (reason, p) => {
    console.error(reason, 'Unhandled Rejection at Promise', p);
  })
  .on('uncaughtException', (err) => {
    console.error('Uncaught Exception thrown', err);
    cleanup();
    process.exit(1);
  });

void async function start () {
  const listener = server.listen(config.app.port, (data) => {
    console.log('Server started on port: %d', listener.address().port);
  });
}();
